package com.mzpai.web.controller;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.gexin.fastjson.JSONObject;
import com.mzpai.product.constant.WXCommonConstants;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.model.StoreCategory;
import com.mzpai.product.model.SystemAdmin;
import com.mzpai.product.model.SystemSetting;
import com.mzpai.product.model.SystemStore;
import com.mzpai.product.service.StoreCategoryService;
import com.mzpai.product.service.SystemAdminService;
import com.mzpai.product.service.SystemSettingService;
import com.mzpai.product.service.SystemStoreService;
import com.mzpai.product.util.ImageMergeUtil;
import com.mzpai.product.util.WxQrCodeUtil;
import com.mzpai.product.vo.ShareStoreInfoVo;
import com.mzpai.product.vo.SystemStoreVo;
import com.mzpai.util.DateUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;
import com.mzpai.web.utils.StorageUploadUtil;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 *
 * <b>门店基本信息 | Controller</b><br>
 *
 * yanglijun 2021-03-20 09:53:39
 * 
 *  @version 1.0.0
 *
 */
@Api(value = "门店注册接口")
@Controller
@RequestMapping("/store")
public class SystemStoreController extends BaseController {
	@Autowired 
	private StoreCategoryService storeCategoryService;
	@Autowired 
	private SystemStoreService systemStoreService;
	@Autowired 
	private SystemAdminService systemAdminService;
	@Value("${mzpai.share.storeUrl}")
	private String shareStoreUrl;
	
	private static Logger log = LoggerFactory.getLogger(SystemStoreController.class);
	private String defaultUrl = "http://cdn.bianwaixingqiu.com/1c6b9202010172205457639.png";
	
	@Autowired
	private SystemSettingService systemSettingService;
	
	
	/** 
	*
	* 门店申请保存
	* @throws Exception
	*/
	@ApiOperation(value = "门店申请保存")
	@RequestMapping(value = "/createStore")
	@ResponseBody
	public ResponseVo<SystemStoreVo> createStore(@RequestParam(value = "storeStr", required = true) String storeStr) throws Exception {
		log.info("msg=对象信息={}", storeStr );
		SystemStoreVo vo = JSONObject.parseObject(storeStr, SystemStoreVo.class);
		ResponseVo<SystemStoreVo> resp = new ResponseVo<SystemStoreVo>();
		if(vo == null || vo.getAccount() == null) {
			resp.setCode(0);
			resp.setMessage("对象信息为空,或者account为空！");
			resp.setResult(null);
		} else {
			SystemStore target = new SystemStore();
			BeanUtil.copyProperties(vo, target);
			//设置必填
			target.setIntroduction("");
			target.setAddress("");
			target.setValidTime("");
			target.setCid("1");
			target.setTotalMoney(0D);
			target.setSettleMoney(0D);
			target.setNowMoney(0D);
			target.setIsShow(1);
			target.setIsDel(0);
			target.setSales("0");
			target.setIsRecommend("0");
			target.setSort(0);
			//设置坐标系逆编码
			addTargetAddress(target);
			target.setAddTime(DateUtil.getUTCTime(null).intValue());
			
			//设置图片默认值
			addDefaultImage(target);
			
			int storeId = systemStoreService.save(target);
			vo.setId(storeId);
			vo.setStoreUrl(shareStoreUrl + storeId);
			//绑定门店管理员与门店关系
			updateSystemAdmin(vo);
			
			//创建默认分类
			addStoreCate(storeId);
			
			resp.setCode(200);
			resp.setMessage("保存成功！");
			resp.setResult(vo);
		}
		return resp;
	}
	
	private void addTargetAddress(SystemStore target) {
		if(StringUtils.isNoneBlank(target.getLongitude()) && StringUtils.isNoneBlank(target.getLatitude())) {
			try{
				Map<String, String> map = StringUtils.getAddr(target.getLongitude(), target.getLatitude());
				target.setLocationProvince(map.get("province"));
				target.setLocationCity(map.get("city"));
				target.setLocationDistrict(map.get("district"));
			} catch(Exception e) {
				
			}
		}
		
	}

	/**
	 * 门店下没有分类，创建分类
	 * @param storeId
	 */
	private void addStoreCate(int storeId) {
		List<StoreCategory> list = storeCategoryService.queryByStoreId(storeId);
		if(list.isEmpty()) {
			StoreCategory target = new StoreCategory();
			target.setPid(0);
			target.setCateName("默认");
			target.setSort(1);
			target.setPic("");
			target.setAddTime(DateUtil.getUTCTime(null).intValue());
			target.setStoreId(storeId);
			target.setCateCode(StringUtils.getRandomCode(8));
			target.setFullCateCode(target.getCateCode());
			storeCategoryService.save(target);
		}
		
	}
	//添加默认页面
	private void addDefaultImage(SystemStore target) {
		target.setImage(StringUtils.isNoneBlank(target.getImage()) ? target.getImage() : defaultUrl);
		target.setBgImage(StringUtils.isNoneBlank(target.getBgImage()) ? target.getBgImage() : defaultUrl);
		target.setImageInput(StringUtils.isNoneBlank(target.getImageInput()) ? target.getImageInput() : "[" + defaultUrl +"]");
		target.setBusinessLicense(StringUtils.isNoneBlank(target.getBusinessLicense()) ? target.getBusinessLicense() : defaultUrl);
	}
	/**
	 * 绑定门店与管理员关系
	 * @param vo
	 */
	private void updateSystemAdmin(SystemStoreVo vo) {
		logger.info("绑定门店关系={},", JSONObject.toJSONString(vo));
		SystemAdmin o = systemAdminService.queryBySim(vo.getAccount());
		SystemAdmin upAdmin = new SystemAdmin();
		upAdmin.setId(o.getId());
		upAdmin.setStoreId(vo.getId() + "");
		systemAdminService.update(upAdmin);
	}

	/** 
	*
	* 门店编辑接口
	* @throws Exception
	*/
	@ApiOperation(value = "门店编辑接口")
	@RequestMapping(value = "/updateStore")
	@ResponseBody
	public ResponseVo<SystemStoreVo> updateStore(@RequestParam(value = "storeStr", required = true) String storeStr) throws Exception {
		log.info("msg=对象信息={}", storeStr );
		SystemStoreVo vo = JSONObject.parseObject(storeStr, SystemStoreVo.class);
		ResponseVo<SystemStoreVo> resp = new ResponseVo<SystemStoreVo>();
		if(vo == null) {
			resp.setCode(0);
			resp.setMessage("对象信息为空！");
			resp.setResult(null);
		} else {
			SystemStore target = new SystemStore();
			BeanUtil.copyProperties(vo, target);
			//设置图片默认值
			addDefaultImage(target);
			//设置坐标系逆编码
			addTargetAddress(target);
			systemStoreService.update(target);
			
			Integer  storeId=vo.getId();
			vo.setStoreUrl(shareStoreUrl + storeId);
			
			resp.setCode(200);
			resp.setMessage("保存成功！");
			resp.setResult(vo);
		}
		return resp;
	}
	
	/** 
	*
	* 查询列表 
	* @throws Exception
	*/
	@ApiOperation(value = "门店查询接口，根据ID查询")
	@RequestMapping(value = "/queryByStoreId")
	@ResponseBody
	public ResponseVo<SystemStoreVo> queryByStoreId(@RequestParam(value = "storeId", required = true) String storeId) throws Exception {
		ResponseVo<SystemStoreVo> res=new ResponseVo<SystemStoreVo>();
		res.setCode(0);
		if(StringUtils.isNoneBlank(storeId)) {
			SystemStore o = systemStoreService.queryById(storeId);
			SystemStoreVo vo = new SystemStoreVo();
			BeanUtil.copyProperties(o, vo);
			res.setCode(200);
			res.setResult(vo);
		}
		return res;
	}
	
	
	
	@ApiOperation(value = "分享店铺信息")
    @RequestMapping(value = "/queryShareStoreInfo", method = {RequestMethod. POST ,RequestMethod. GET})
	@ResponseBody
    public ResponseVo<ShareStoreInfoVo> queryShareStoreInfo(
    		@ApiParam(required = true, name = "storeId", value = "门店storeId")
    		@RequestParam(value = "storeId", required = true) Integer storeId){
		
		log.info("msg1=分享店铺信息,,method=queryShareStoreInfo,,storeId={}",storeId);
		
		ResponseVo<ShareStoreInfoVo> resVo=new ResponseVo<ShareStoreInfoVo>();
		
		if(storeId==null){
			resVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			return resVo;
		}
		
		SystemStore systemStore=systemStoreService.queryByPrimaryId(storeId);
		
		ShareStoreInfoVo shareStoreInfoVo=new ShareStoreInfoVo();
		
		//门店信息
		String storeName=systemStore.getName();
		shareStoreInfoVo.setId(storeId);
		shareStoreInfoVo.setStoreName(storeName);
		String logoImage=systemStore.getImage();
		
		if(systemStore!=null){
//			vo.setStoreUrl(shareStoreUrl + storeId);
			//获取门店小程序二维码
			
			String shareImage=systemStore.getWechatappletQrcodeShareImage();
			
			String lastMergImageUrl=null;
			
//			if(StringUtils.isNullOrBlank(shareImage)){
				String token=null;
				try {
					token = WxQrCodeUtil.postToken(WXCommonConstants.appId, WXCommonConstants.AppSecret);
				} catch (Exception e) {
					e.printStackTrace();
					resVo.setCode(ProductResExceptionCode.GET_TOKEN_ERROR.getCode());
					resVo.setMessage(ProductResExceptionCode.GET_TOKEN_ERROR.getMessage());
					return resVo;
				}
				 
				 String scene="storeId="+storeId;
				 
				 
				 SystemSetting systemSetting = systemSettingService.getSettingByCode("storeshareurl");
				 String value=systemSetting.getValue();
				 InputStream in=null;
				 if(value.equals("2")){
					 logger.info("msg1=小程序路径,,method=queryShareStoreInfo,,path=pages/home/home");
					 in=WxQrCodeUtil.generateQrCode("pages/home/home", scene, token);
					 
				 }else{
					 logger.info("msg1=小程序路径,,method=queryShareStoreInfo,,path=pages/store/storeDetail/storeDetail");
					 in=WxQrCodeUtil.generateQrCode("pages/store/storeDetail/storeDetail", scene, token);
				 }
//				 InputStream in=WxQrCodeUtil.generateQrCode("pages/store/storeDetail/storeDetail", scene, token);
				 
//				 InputStream in=WxQrCodeUtil.generateQrCode("pages/home/home", scene, token);
				 
				 BufferedImage qrCodeBufferImage = null;
				 try {
					qrCodeBufferImage = ImageIO.read(in);
				} catch (IOException e) {
					e.printStackTrace();
					resVo.setCode(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getCode());
					resVo.setMessage(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getMessage());
					return resVo;
				}
				 
//		        String logoUrl="https://thirdwx.qlogo.cn/mmopen/vi_32/gjEcX8W0yxtN2mbhY7MuyYdOCUbyAnZjCpmY2VhG7PBZK8a8G7JiajmTCKBHjERtsxgEY9zR7icKpYbZbTV9ASGA/132";
		        String logoUrl=logoImage;
		        BufferedImage newsunImage=ImageMergeUtil.replaceSunCodeLogo (qrCodeBufferImage,logoUrl);
		        
		        //bufferedimage 转换成 inputstream
		        ByteArrayOutputStream bs = new ByteArrayOutputStream();
				try {
					ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
					ImageIO.write(newsunImage, "jpg", imOut);
				    InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
				    lastMergImageUrl=StorageUploadUtil.ossUploadFile(inputStream, "jpg");
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("msg1=生成门店分享二维码失败,,method=queryShareStoreInfo");
					resVo.setCode(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getCode());
					resVo.setMessage(ProductResExceptionCode.GET_QRCODE_IMAGE_ERROR.getMessage());
					return resVo;
				}
//			}else{
//				lastMergImageUrl=shareImage;
//			}
	        logger.info("msg1=分享店铺信息,聚合图片路径,,method=queryShareStoreInfo,,lastMergImageUrl={}",lastMergImageUrl);
	        
			shareStoreInfoVo.setQrcodeShareImage(lastMergImageUrl);
			SystemStore updateSystemStore=new SystemStore();
			updateSystemStore.setId(storeId);
			updateSystemStore.setWechatappletQrcodeShareImage(lastMergImageUrl);
			systemStoreService.update(updateSystemStore);
		}else{
			resVo.setCode(ProductResExceptionCode.STOREINFO_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.STOREINFO_NULL.getMessage());
			return resVo;
		}
		logger.info("msg1=分享店铺信息,,method=queryShareStoreInfo,,shareStoreInfoVo={}",JSON.toJSONString(shareStoreInfoVo));
		resVo.setResult(shareStoreInfoVo);
		return resVo;
    }
	
	/**
	 * 文件下载
	 * @param destination  下载路径
	 * @param input
	 * @throws IOException
	 */
  public static void writeToLocal(String destination, InputStream input)
			throws IOException {
	int index;
	byte[] bytes = new byte[1024];
	FileOutputStream downloadFile = new FileOutputStream(destination);
	while ((index = input.read(bytes)) != -1) {
		downloadFile.write(bytes, 0, index);
		downloadFile.flush();
	}
	input.close();
	downloadFile.close();

	}
  
  
  @ApiOperation(value = "测试上传")
  @RequestMapping(value = "/testImage", method = {RequestMethod. POST ,RequestMethod. GET})
	@ResponseBody
  public ResponseVo<String> testImage(
  		@ApiParam(required = true, name = "path", value = "路径")
  		@RequestParam(value = "path", required = true) String path) throws Exception{
		log.info("msg1=测试上传开始,,method=testImage,,path={}",path);
		ResponseVo<String> resVo=new ResponseVo<String>();
		File file=new File(path);
		String lastMergImageUrl=StorageUploadUtil.ossUploadFile(file, "jpg");
		log.info("msg1=测试上传结束,,method=testImage,,lastMergImageUrl={}",lastMergImageUrl);
		resVo.setResult(lastMergImageUrl);
		return resVo;
  }
  
  
	
	
}